use bevy::asset::{AssetServer, Assets, Handle};
use bevy::image::{Image, ImageAddressMode, ImageSampler, ImageSamplerDescriptor};
use bevy::pbr::StandardMaterial;
use bevy::prelude::{default, EventReader, FileDragAndDrop, Query, Res, ResMut, Window};

pub(crate) fn file_drag_and_drop_system(
    mut events: EventReader<FileDragAndDrop>,
    asset_server: Res<AssetServer>,
    mut assets_images: ResMut<Assets<Image>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut game_assets: ResMut<crate::scene::scene_initial::InLineAssets>,
) {
    for event in events.read() {

        let handle: Handle<Image> = match event {
            FileDragAndDrop::DroppedFile { window,path_buf } => {
                let path = path_buf.to_string_lossy().to_string();
                asset_server.load_override(path)
            }
            _=>{
                asset_server.load_override("default_image.png")
            }
        };
        
        // 设置纹理采样器
        if let Some(image) = assets_images.get_mut(&handle) {
            image.sampler = ImageSampler::Descriptor(ImageSamplerDescriptor {
                address_mode_u: ImageAddressMode::ClampToEdge,
                address_mode_v: ImageAddressMode::ClampToEdge,
                ..default()
            });
        }
        
        game_assets.photo_frame = handle.clone_weak();
        
        if let Some(material) = materials.get_mut(&game_assets.material){
            material.base_color_texture = Some(handle);
        }
    }
}